/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 上下文
 * 必传参数，子类定义；动态参数，写入map
 *
 * @author Coulson
 * @since 2025/3/26
 */
public abstract class Context {

    private final Map<String, Object> context;

    public Context() {
        context = new HashMap<>();
    }

    public void add(String key, Object value) {
        context.put(key, value);
    }

    public void add(Map<String, Object> params) {
        if (null == params || params.isEmpty()) {
            return;
        }
        this.context.putAll(params);
    }

    public Map<String, Object> getContext() {
        return this.context;
    }

    public Object get(String key) {
        return this.context.get(key);
    }

    /**
     * 等同于下面方式
     * List<?> list = (List<?>) context.get(key);
     * for (Object obj: list) {
     *     T t = (T) obj;
     * }
     */
    public <T> List<T> getList(String key, Class<T> clazz) {
        Object val = this.context.get(key);
        if (val instanceof Collection<?>) {
            List<T> list = new ArrayList<>();
            for (Object obj : (Collection<?>) val) {
                if (clazz.isInstance(obj)) {
                    list.add(clazz.cast(obj));
                }
            }
            return list;
        }
        return Collections.emptyList();
    }

    public boolean contains(String key) {
        return this.context.containsKey(key);
    }

    public void remove(String key) {
        this.context.remove(key);
    }

    public void remove(List<String> keys) {
        for (String key : keys) {
            this.context.remove(key);
        }
    }

    public void clear() {
        this.context.clear();
    }

}
